<template>
    <div class="login-box">
        <el-card>
            <h1>欢迎登录</h1>
            <!-- 登录表单 -->
            <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules">
                <el-form-item label="账号" prop="username">
                    <el-input v-model="ruleForm.username" />
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input type="password" v-model="ruleForm.password" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="submitForm(ruleFormRef)">
                        登录
                    </el-button>
                    <el-button @click="resetForm(ruleFormRef)">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>
    </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'

import type { FormInstance, FormRules } from 'element-plus'
// 导入 自定义类型 LoginForm
import type { LoginForm } from '@/types'
// 表单实例
const ruleFormRef = ref<FormInstance>()
// 表单数据对象：和表单双向绑定的数据
const ruleForm = ref<LoginForm>({
    username: '',
    password: ''
})
// 校验规则
const rules = ref<FormRules<LoginForm>>({
    username: [
        { required: true, message: '请输入账号', trigger: 'blur' },
        { min: 4, max: 8, message: '长度必须为4-8位', trigger: 'blur' },
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 4, max: 8, message: '长度必须为4-8位', trigger: 'blur' },
    ],
})

// 导入登录的API
import { loginAPI } from '@/api'
// 导入ElMessage组件
import { ElMessage } from 'element-plus'
// 导入useRouter函数
import { useRouter } from 'vue-router'
const router = useRouter()
// 登录方法
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            // 表单验证通过了，调用登录API
            let res = await loginAPI(ruleForm.value)
            // 根据返回值中是否存在token，判断登录是否成功
            if (res.data.data) {
                // 将token保存到本地存储空间
                localStorage.setItem('token', res.data.data)
                // 消息提示
                ElMessage.success(res.data.msg)
                // 跳转到首页
                router.push('/index')
            } else {
                // 消息提示
                ElMessage.error(res.data.msg)
            }
        } else {
            console.log('error submit!', fields)
        }
    })
}
// 重置方法
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}
</script>

<style scoped>
.login-box {
    width: 480px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}
</style>